package com.yeban.issue;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

/**
 * @Desc TODO
 * @Author yeban
 * @Date 2025/10/7
 */
// n皇后
public class NQueen {

    List<List<String>> res = new ArrayList<>();

    public void backTrack(int n, int row, char[][] chessBoard) {

        // 存放结果
        if(row == n) {
            res.add(Array2List(chessBoard));
            return;
        }

        // 判断第row行的第i个位置放置的皇后是否合理
        for(int col = 0; col < n; col ++) {
            if(isValid(row,col,chessBoard,n)) {
                chessBoard[row][col] = 'Q'; // 放置皇后
                backTrack(n,row+1,chessBoard);
                chessBoard[row][col] = '.'; // 撤销皇后
            }
        }
    }

    public List Array2List(char[][] chessBoard) {

        List<String> list = new ArrayList<>();

        for (char[] c : chessBoard){    // 有多少行
            list.add(String.valueOf(c));
        }
        return list;
    }

    public boolean isValid(int row, int col, char[][] chessBoard, int n) {

        // 检查列
        for (int i = 0; i < row; i++) {    // 剪枝
            if(chessBoard[i][col] == 'Q') {
                return false;
            }
        }
        
        // 检查反对角线
        for (int i = row - 1, j = col - 1; i >= 0 && j >= 0 ; i--, j--) {
            if(chessBoard[i][j] == 'Q') {
                return false;
            }
        }

        // 检查正对角线
        for (int i = row - 1, j = col + 1; i >= 0 && j <= 0 ; i--, j++) {
            if(chessBoard[i][j] == 'Q') {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {

        NQueen nQueen = new NQueen();
        System.out.println("请输入n：");
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        char[][] chessBoard = new char[n][n];

        for(char[] c : chessBoard) {
            Arrays.fill(c,'.');
        }

        nQueen.backTrack(n,0,chessBoard);
        System.out.println(nQueen.res);

    }
}
